var time = require('../../utils/util.js');
wx.cloud.init()
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',//新闻的id
    info: '', //新闻的所有记录对象
    status:'新闻',//新闻 广告 恋爱课堂
    //以下为编辑器的需要
    formats: {},
    bottom: 0,
    readOnly: false,
    placeholder: '开始输入...',
    _focus: false,
    array: [],
    objectArray: [],
    index: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.data.id=options.id
    console.log(options.id)
  },
  search: function(s) {
    /**按编码搜索 */
    wx.navigateTo({
      url: '../a_search/a_search?bianhao=' + s.detail.value,
    })
  },
  radio:function(e){
    /**选择radio */
      this.data.status=e.detail.value
    },
  formSubmit(e) {
    var that = this
    that.editorCtx.getContents({
      success(res) {
        console.log('内容:', res.html)
        console.log('标题:', e.detail.value.title)
        var text = res.html; //内容
        var title = e.detail.value.title; //标题

        if (typeof(title) == "undefined" || title == 0) {
          wx.showToast({
            title: '文章标题不能为空',
            icon: 'none'
          })
          return;
        }

        db.collection('loveclass').doc(that.data.id).update({
            data: {
              title: title,
              text: text,
              status:that.data.status
            }
          })
          .then(res => {
            wx.showModal({
              title: '提示',
              content: '修改成功',
              success(res) {
                wx.navigateBack({
                  delta: 1,
                })
              }
            })
          })

      }
    })
  },
  bindPickerChange(e) {
    // 选择了课程类别
    console.log(e.detail.value)
    this.setData({
      index: e.detail.value
    })

  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onEditorReady() {
    console.log('form')
    var admin_openid = wx.getStorageSync('admin_openid')
    var admin_authority = wx.getStorageSync('authority')//红娘还是管理员
    if (typeof (admin_openid) == "undefined" || admin_openid == 0 || typeof (admin_authority) == "undefined" || admin_authority == 0) {
      wx.reLaunch({
        url: '/pages/admin/admin',
      })
    } else if (admin_authority != '管理员') {
      wx.showModal({
        title: '权限不足',
        content: '您无权访问该页',
        success(res) {
          wx.reLaunch({
            url: '/pages/admin/admin',
          })
        }
      })

    } else {
      //获取新闻详情
      const that = this
      wx.createSelectorQuery().select('#editor').context(function (res) {
        that.editorCtx = res.context

        /**操作数据库获取新闻详情 */
        db.collection('loveclass').doc(that.data.id).get().then(res2 => {
          console.log(res2)
          that.editorCtx.setContents({
            html: res2.data.text
          })
          that.setData({
            info: res2.data
          })
        })


      }).exec()
    }


 
  },

  undo() {
    this.editorCtx.undo()
  },
  redo() {
    this.editorCtx.redo()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function() {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function(res) {
        console.log("clear success")
      }
    })
  },
  removeFormat(e) {
    console.log(e)
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {

    const that = this
    wx.chooseImage({
      count: 1,
      success: function(res) {
        //把图片上传到云空间
        wx.showLoading({
          title: '正在上传图片',
        })
        wx.cloud.uploadFile({
          cloudPath: `news/upload/${time.formatTime(new Date)}/${Math.floor(Math.random() * 100000000)}.png`, // 上传至云端的路径
          filePath: res.tempFilePaths[0], // 临时文件路径
          success: cover => {
            //上传成功了,把他返回到编辑器

            that.editorCtx.insertImage({
              src: cover.fileID,
              data: {
                id: cover.fileID,
                role: 'god'
              },
              success: function() {
                wx.hideLoading()
              }
            })
            //插入编辑器结束

          }
        })
        //云文件上传结束

      }
    })
    //选择图片结束
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})